package it.intecs.pisa.smarcos.base;

import it.intecs.pisa.smarcos.R;
import it.intecs.pisa.smarcos.R.raw;

import java.io.IOException;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.util.Log;


public final class BeepManager {

	private static final String TAG = BeepManager.class.getSimpleName();

	private static BeepManager instance;

	Context context;
	private static final float BEEP_VOLUME = 0.10f;
	private MediaPlayer mediaPlayer;


	public static BeepManager getInstance(Context con){
		Log.d(TAG, "getInstance");

		if(instance==null)
			instance=new BeepManager(con);

		return instance;
	}

	public static void nullInstance(){
		instance = null;
	}

	private BeepManager(Context con) {

		this.context = con;       	

		mediaPlayer = new MediaPlayer();
		mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		// When the beep has finished playing, rewind to queue up another one.
		mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
			public void onCompletion(MediaPlayer player) {
				player.seekTo(0);
			}
		});

		AssetFileDescriptor file = context.getResources().openRawResourceFd(R.raw.beep);
		try {
			mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
			file.close();
			mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
			mediaPlayer.prepare();
		} catch (IOException ioe) {
			Log.w(TAG, ioe);
			mediaPlayer = null;
		}
	}

	public void playBeepSound() {
		if (mediaPlayer != null) {
			mediaPlayer.start();
		}
	}
}
